//
//  JFSearchViewController.m
//  UISearchControllerDemo
//
//  Created by Alan Wang on 2018/11/5.
//  Copyright © 2018 zhoubo. All rights reserved.
//

#import "JFSearchViewController.h"

@interface JFSearchViewController ()<UISearchBarDelegate,UISearchResultsUpdating,UISearchControllerDelegate>

@property (strong, nonatomic) UISearchController *searchController;
@property (strong, nonatomic) UITableView *tableView;
@property (strong, nonatomic) UISearchBar *searchBar;
@property (strong,nonatomic)  UITextField * inputTextField;

@end

@implementation JFSearchViewController
-(instancetype)initWithDataSoure:(id<UITableViewDelegate,UITableViewDataSource,JFSearchViewControllerSearchResultsDelegate>) delegate{
    self = [super init];
    if(self){
        self.delegate =  delegate;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self searchController];
    [self.view addSubview:self.tableView];
    self.view.backgroundColor = HexColor(@"#ffffff");
    if (@available(iOS 11.0, *)) {
     self.automaticallyAdjustsScrollViewInsets = NO;
    }
    self.definesPresentationContext = YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    if(self.becomeFirstResponder){
        [self showKeyboard];
    }
    _nav = self.navigationController;
}

-(void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    if(self.searchController.isActive) {
        if([self isFullScreen]){
            [self.tableView setContentInset:UIEdgeInsetsMake(43, 0, 0, 0)];
        }else{
            if (@available(iOS 11.0, *)) {
                 [self.tableView setContentInset:UIEdgeInsetsMake(10, 0, 0, 0)];
            }else{
                 [self.tableView setContentInset:UIEdgeInsetsMake(15, 0, 0, 0)];
            }
           
        }
    }else {
          [self.tableView setContentInset:UIEdgeInsetsMake(0, 0, 0, 0)];
    }

    UINavigationBar * bar = self.navigationController.navigationBar;
    if(bar){
        bar.translucent = NO;
    }
}
#pragma mark--懒加载
-(UITableView*)tableView{
    if(!_tableView){
        _tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
        _tableView.backgroundColor = [UIColor yellowColor];
        _tableView.alpha = 1;
        _tableView.delegate = self.delegate;
        _tableView.dataSource = self.delegate;
        _tableView.tableFooterView = [UIView new];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _tableView.estimatedRowHeight = 0;
            _tableView.estimatedSectionHeaderHeight = 0;
            _tableView.estimatedSectionFooterHeight = 0;
        }else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
        self.tableView.tableHeaderView = self.searchController.searchBar;
    }
    return _tableView;
}

-(UISearchController*)searchController{
    if(!_searchController){
        _searchController = [[UISearchController alloc]initWithSearchResultsController:nil];
        _searchController.searchResultsUpdater = (id)self;
        _searchController.searchBar.delegate = self;
        _searchController.delegate = self;
        [_searchController.searchBar sizeToFit];
        _searchController.searchBar.placeholder = @"搜索";
        [_searchController.searchBar sizeToFit];
        _searchBar = _searchController.searchBar;
        [self searchBarStyle:_searchBar];

        WEAKSELF
         [_searchController.searchBar changeSearchTextFieldWithCompletionBlock:^(UITextField * _Nonnull textField) {
             weakSelf.inputTextField = textField;
         }];

         self.definesPresentationContext = YES;
    }
    _searchController.dimsBackgroundDuringPresentation = self.dimsBackgroundDuringPresentation;
    return _searchController;
}

-(void)setRightBtnWordsColor:(UIColor *)rightBtnWordsColor{
    if(rightBtnWordsColor){
        _rightBtnWordsColor = rightBtnWordsColor;
        if(!_searchBar){
            [self searchController];
        }
        _searchBar.tintColor = _rightBtnWordsColor;
    }
}
-(void)setBackgroundColor:(UIColor *)backgroundColor{
    if(backgroundColor){
        _backgroundColor = backgroundColor;
        if(!_searchBar){
            [self searchController];
        }
        _searchBar.barTintColor = _backgroundColor;
    }
}
-(void)setInputView:(UIView *)inputView{
    if(inputView){
        _inputView = inputView;
        if(!_searchBar){
            [self searchController];
        }
       _inputTextField.inputView = _inputView;
    }
}
-(void)setInputAccessoryView:(UIView *)inputAccessoryView{
    if(inputAccessoryView){
        _inputAccessoryView = inputAccessoryView;
        if(!_searchBar){
            [self searchController];
        }
        _inputTextField.inputAccessoryView = inputAccessoryView;
    }
}
-(void)setPlaceholder:(NSString *)placeholder{
    if(placeholder&&placeholder.length){
        _placeholder = placeholder;
        if(!_searchBar){
            [self searchController];
        }
        _searchBar.placeholder = _placeholder;
        [self.searchController.searchBar sizeToFit];
    }
}
-(void)setPlaceholderColor:(UIColor *)placeholderColor{
    if(placeholderColor){
        _placeholderColor = placeholderColor;
        if(!_searchBar){
            [self searchController];
        }
        
        [_inputTextField setValue:[UIColor greenColor] forKeyPath:@"_placeholderLabel.textColor"];
        _inputTextField.AWattributedPlaceholderQ(_inputTextField.placeholder, placeholderColor, nil);

    }
}
-(void)setTxtBackgroundColor:(UIColor *)txtBackgroundColor{
    if(txtBackgroundColor){
        _txtBackgroundColor = txtBackgroundColor;
        if(!_searchBar){
            [self searchController];
        }
        [_inputTextField setBackgroundColor:txtBackgroundColor];
    }
}
-(void)setSearchText:(NSString *)searchText{
    if(searchText){
        _searchText = searchText;
        if(!_searchBar){
            [self searchController];
        }
        [_inputTextField setText:searchText];
    }
}
-(void)setDelegate:(id<UITableViewDelegate,UITableViewDataSource,JFSearchViewControllerSearchResultsDelegate>)delegate{
    if(delegate){
        _delegate = delegate;
    }
}
-(BOOL)active{
    return self.searchController.isActive;
}
#pragma mark--辅助方法
- (BOOL)isFullScreen {
    if (@available(iOS 11.0, *)) {
        if ( self.view.safeAreaInsets.bottom == 34) {
            return YES;
        }else{
            return NO;
        }
    }
    return NO;
}
-(void)showKeyboard{
    self.searchController.active = YES;
    [self.searchController.searchBar becomeFirstResponder];
    if(self.searchText && self.searchText.length){
        self.searchController.searchBar.text = self.searchText;
    }
}
#pragma mark--searchBarDelegate
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    [searchBar setShowsCancelButton:YES animated:YES];
    [self searchBarStyle:searchBar];
    return YES;
}

-(void)searchBarStyle:(UISearchBar *)searchBar{
    for (id obj in [searchBar subviews]) {
        if ([obj isKindOfClass:[UIView class]]) {
            for (id obj2 in [obj subviews]) {
                if ([obj2 isKindOfClass:[UIButton class]]) {
                    UIButton *btn = (UIButton *)obj2;
                    if(self.rightBtnWords&&self.rightBtnWords.length){
                        [btn setTitle:self.rightBtnWords forState:UIControlStateNormal];
                    }
                    if(self.rightBtnWordsColor){
                        [btn setTitleColor:self.rightBtnWordsColor forState:UIControlStateNormal];
                    }
                }
                if([NSStringFromClass([obj2 class]) isEqual:@"UISearchBarTextField"]){
                    UITextField * textfide = (UITextField*)obj2;
                    if(self.txtColor){
                        [textfide setTextColor:self.txtColor];
                    }
                    if(self.cursorColor){
                        [textfide setTintColor:self.cursorColor];
                    }
                }
            }
        }
    }
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    if([self.delegate respondsToSelector:@selector(searchBarSearchButtonClicked)]){
        [self.delegate searchBarSearchButtonClicked];
    }
}
#pragma mark--UISearchResultsUpdating
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController{
    searchController.searchResultsController.view.hidden = NO;
    NSString * searchText = searchController.searchBar.text;
    _searchText = searchText;
    
    if([self.delegate respondsToSelector:@selector(updateSearchResults:)]){
        [self.delegate updateSearchResults:_searchText];
    }
    [self.tableView reloadData];
   
}
-(void)reloadData{
     [self.tableView reloadData];
}
@end
